<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\BaseController;
use app\model\Order as OrderModel;
use app\model\OrderDetail;
use app\model\Sale as SaleModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class Order extends BaseController
{
    public function index()
    {
        $order_no=request()->param('order_no');
        $order_type=request()->param('order_type');
        $status=request()->param('status');
        $time=request()->param('time');

        $data=OrderModel::when($order_no,function ($query) use($order_no){
            $query->where('order_no',$order_no);
        })->when($time,function ($query) use($time){
            $start=strtotime(explode(',',$time)[0]);
            $end=strtotime(explode(',',$time)[1]);
            $query->whereBetween('created_at',[$start,$end]);
        })->when($order_type,function ($query) use($order_type){
            $query->where('order_type',$order_type);
        })->when($status,function($query) use($status){
            if(in_array($status,[10,20,50])){
                $query->where('status',$status);
            }})->with('detail.product')
        ->order('id','desc')->paginate(10);
        $start=strtotime(date('Y-m-d'));
        $end=strtotime(date('Y-m-d 23:59:59'));
        $money['today']=OrderModel::whereBetween('created_at',[$start,$end])->sum('pay_price');
        $money['totalprices']=OrderModel::sum('pay_price');
        return $this->success(compact('data','money'));
    }

    public function create()
    {
      $data=request()->param();

      foreach ($data as $item){
         $model= OrderModel::create([
              'order_no'=>$this->createOrderNo1(),
              'status'=>OrderModel::STATUS_SUCCESS,
              'users_id'=>$item['users_id'],
              'pay_price'=>$item['total'],
              'pay_mode'=>3,
          ]);

        OrderDetail::create([
            'order_id'=>$model->id,
            'product_id'=>$item['id'],

        ]);
      }
    return $this->success();
    }

    public function over()
    {
        $id=request()->param('id');
        OrderModel::where('id',$id)->update(['status'=>OrderModel::STATUS_SUCCESS]);
    }

    public function bill()
    {

        $id=request()->param('id');
        $data=OrderModel::where('id',$id)->with('detail.product')->find();
        $type=[1=>'Paypal',2=>'錢包',3=>'線下'];
        $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);

        $pdf->SetCreator('My Application');
        $pdf->SetAuthor('John Doe');
        $pdf->SetTitle('My PDF');
        $pdf->SetSubject('Test');

        // Set header

        $pdf->SetHeaderData('', 0, '電子發票', '');
        $pdf->setHeaderFont(['stsongstdlight', '', '10']);
        // Add a page
        $pdf->AddPage();

        // Write some content
        $pdf->SetFont('stsongstdlight', '', 12);
        $pdf->Write(5, "訂單號：$data->order_no");
        $pdf->Ln(); // Add a line break
        $pdf->Write(5, "價格：$data->pay_price");
        $pdf->Ln(); // Add a line break
        $pdf->Write(5,"下單時間：$data->created_at");
        $pdf->Ln(); // Add a line break
        $pdf->Write(5,"支付方式：{$type[$data->pay_mode]}");
        $pdf->SetY(50);
        $pdf->SetFont('stsongstdlight', 'B', 12);
        $pdf->Cell(50, 10, '產品名稱', 1, 0, 'C');
        $pdf->Cell(30, 10, '數量', 1, 0, 'C');
        $pdf->Cell(30, 10, '價格', 1, 0, 'C');
        $pdf->Ln();


// Add table rows
        $pdf->SetFont('stsongstdlight', '', 12);
        foreach($data->detail as $detail) {
            $product = $detail->product;
            $pdf->Cell(50, 10, $product->name, 1, 0, 'L');
            $pdf->Cell(30, 10, $detail->num, 1, 0, 'C');
            $pdf->Cell(30, 10, $detail->price, 1, 0, 'R');
            $pdf->Ln();
        }
        // Output the PDF as a string
//        $pdfData = $pdf->Output('電子發票.pdf', 'S');
//        $this->success(ossUpload($pdfData));
        // Return the PDF data to the browser
        $name= runtime_path(). '/pdf';

        $fileName= date('YmdHis') . '.pdf';
        $pdf->Output($name.$fileName, 'F');
        return $this->success(ossUpload($name.$fileName));
//        return response($pdfData, 200, [
//            'Content-Type' => 'application/pdf',
//            'Content-Disposition' => 'inline; filename="MyPDF.pdf"',
//        ]);
    }

    public function delete($id)
    {
        return $this->success(OrderModel::where('id',$id)->delete());
    }


    private function createOrderNo1(){
        $date = date('Ymd');
        $rand = mt_rand(1000, 9999); // 生成 4 位随机数
        $chars = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
        shuffle($chars);
        $str = implode('', array_slice($chars, 0, 4)); // 选择 8 个字符生成随机字符串
        return $date . $rand . $str; // 连接日期、随机数和随机字符串
    }

}
